<template>
    <div class="imageSet">
        <BoxWithTitle class="left-wrapper" title="目录" icon="&#xe6f2;" isOther>
            <template #other>
                <el-select v-model="stationId" placeholder="请选择" size="small" class="form-item" @change="onGetMenuList()" style="width:160px">
                    <el-option v-for="item in stationList" :key="item.id" :label="item.stationName" :value="item.id"></el-option>
                </el-select>
            </template>
            <div class="menu-tree">
                <el-button v-if="menuList.length == 0" type="primary" size="small" style="margin: 80px 0 0 120px;" @click="handleAddMenu({node:{}},0,1)">新增目录</el-button>
                <treeMenu :treeData="menuList" name="lable" ref="treeMenu" nodeKey="id" expandALL @menuLeftClick="handleChangeMenu" isRightMenu
                @addMenuItem="handleAddMenu"
                @delMenuItem="handleDelTreeMenu"
                @editMenuItem="handleAddMenu"/>
            </div>
        </BoxWithTitle>

        <ImageViewer
            :imageUrl="imageUrl"
            :graphTreeID="treeID"
            :selectDrawType="selectDrawType"
            :allElementPoint="allElementPoint"
            :allElementText="allElementText"
            @image-loaded="handleImageLoaded"
        />

        <ToolPanel
            :selectDrawType="selectDrawType"
            :allElementPoint="allElementPoint"
            :allElementText="allElementText"
            :drawType="drawType"
            @change-draw-type="handleChangeDrawType"
            @draw-image-type="handleChangeDrawImageType"
            isSet
        />

         <!-- 弹窗组件 -->
        <correlationDialog
            :visible.sync="pointCorrelationDialog"
            :stationId="stationId"
            @associationSave="handleAssociation"
        />

        <directionDialog 
            :visible.sync="directionDialogVisible"
            :angleForm="angleForm"
            @cancel="handleCancelDir"
            @confirm="handleSaveDir"
        />

        <drawSetDialog 
            :visible.sync="drawSetDialogVisible"
            :drawType="drawType"
            :pointLinkList="pointsLink"
            :pointGroup="pointGroup"
            :compGroup="compGroup"
            :treeID="treeID"
            @savePointGroup="handleSavePointGroup"
            @saveCompGroup="handleSaveCompGroup"
        />


        <el-dialog title="目录配置" :visible.sync="dialogPointMenuVisible" width="700px" v-dialogDrag :before-close="handleCancelPointMenu">
            <div class="dialog-body">
                <el-form :model="pointMenuForm" size="medium" label-position="top">
                    <el-form-item label="目录名称" class="form-item-custom" required>
                    <el-input 
                        v-model="pointMenuForm.treeName" 
                        placeholder="请输入目录名称"
                        prefix-icon="el-icon-edit"
                        class="custom-input">
                    </el-input>
                    <div class="input-tips">建议使用简洁明了的名称</div>
                    </el-form-item>
                    
                    <el-form-item label="图表类型" class="form-item-custom" required>
                    <div class="type-selector">
                        <div 
                        v-for="type in graphTypes" 
                        :key="type.value"
                        :class="['type-card', { active: pointMenuForm.graphtype === type.value }]"
                        @click="pointMenuForm.graphtype = type.value">
                        <div class="type-icon">
                            <i class="iconfont" v-html="type.icon"></i>
                        </div>
                        <div class="type-label">{{ type.label }}</div>
                        <div class="type-desc">{{ type.desc }}</div>
                        </div>
                    </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="dialog-footer">
                <el-button 
                    class="cancel-btn" 
                    @click="handleCancelPointMenu"
                    round
                    icon="el-icon-close"
                    size="medium">
                    取消
                </el-button>
                <el-button 
                    type="primary" 
                    class="confirm-btn"
                    @click="handleSavePointMenu"
                    size="medium"
                    round
                    :disabled="!pointMenuForm.treeName">
                    <i class="el-icon-check"></i>
                    保存配置
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import BoxWithTitle from '@/components/base/BoxWithTitle.vue'
import treeMenu from '@/components/base/treeMenu.vue'
import ImageViewer from '@/components/page/setting/imageViewer.vue'
import ToolPanel from '@/components/page/setting/toolPanel.vue'
import correlationDialog from '@/components/page/setting/correlationDialog.vue'
import directionDialog from '@/components/page/setting/directionDialog.vue'
import drawSetDialog from '@/components/page/setting/drawSetDialog.vue'
import { GetStationByCompanyID, GetBWTTree, getLinkInfo,getBwtConfigsByTreeID,GraphPointDraw,setLink,getDIR,GraphPointDIRAdd,GraphPointDIREdit,getGroup,setGroup,getPonits,setCOMP,GraphTreetEdit,GraphTreeAdd,GraphTreeDel } from '@/api/https'
export default ({
    name: 'ImageSetPage',
    components: { BoxWithTitle, treeMenu,ImageViewer,ToolPanel,correlationDialog,directionDialog,drawSetDialog},
    data() {
        return{
            menuList:[],
            stationId:'',
            stationList:[],
            treeID:'',
            currentData:{},
            imageUrl:'',
            allElementPoint:[],
            allElementText:[],
            selectDrawType:0,
            svgW: 0,
            svgH: 0,
            drawType:1,
            pointCorrelationDialog:false,
            directionDialogVisible:false,
            angleForm:{},
            drawSetDialogVisible:false,
            pointsLink:[],
            pointGroup:[],
            compGroup:[],
            dialogPointMenuVisible:false,
            pointMenuForm:{},
            menuEdit:false,
            treeNodeLevel:'',
            graphTypes: [
                {
                value: 1,
                label: '变位图',
                desc: '显示测点的位置变化情况',
                icon: '&#xe6ab;'
                },
                {
                value: 2,
                label: '单矢量',
                desc: '显示单个测点的矢量数据',
                icon: '&#xe708;'
                },
                {
                value: 3,
                label: '合矢量',
                desc: '显示多个测点的矢量数据对比',
                icon: '&#xe75e;'
                }
            ]
        }
    },
    mounted(){
        this.GetStationList()
    },
    methods:{
        GetStationList() {
            GetStationByCompanyID(0).then(res=>{
                if (res.isSuccess) {
                    this.stationList = res.data || []
                    this.stationId = res.data[3]?.id || ''
                    this.onGetMenuList()
                } else {
                    this.stationList = []
                    this.stationId = ''
                }
            })            
        },
        findLeafNodes(data) {
            if (data[0].children == null || data[0].children.length === 0){
                this.treeID = data[0].node.id
                this.currentData = data[0].node
                return
            }else{
                this.findLeafNodes(data[0].children);
            }
        },
        onGetMenuList(id) {
            GetBWTTree({
                StationID:this.stationId,
                CATEGROY:4
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.menuList = res.data
                    this.findLeafNodes(this.menuList);
                    this.$nextTick(()=>{
                        this.$refs.treeMenu.$refs.tree.setCurrentKey(this.treeID);
                        this.handleChangeMenu(this.currentData)
                    })
                    
                }else{
                    this.menuList = []
                }
            });
        },
        handleAddMenu(data,isEdit,treeNodeLevel){
            this.menuEdit = isEdit
            this.treeNodeLevel = treeNodeLevel || ''
            if(isEdit){
                const _editData = Object.assign({},data.node)
                if(_editData.imgUrl && _editData.imgUrl != ''){
                    const imageName = _editData.imgUrl.substring(_editData.imgUrl.lastIndexOf("/")+1)
                    _editData.imgUrl = imageName
                }
                this.pointMenuForm = {..._editData}
            }else{
                this.pointMenuForm = {
                    id: 0,
                    treeID:0,
                    stationID: this.stationId,
                    treeName:'',
                    upTreeID: treeNodeLevel == 1 ? data.node.upTreeID || 0 : data.node.treeID || 0,
                    isBottom:0,
                    graphUrl:data.graphUrl || '',
                    indexId: 0,
                    categroy: 4,
                    imgUrl: '',
                    graphtype:1,
                    imgDate:''
                }
            }
            this.dialogPointMenuVisible = true
        },
        handleDelTreeMenu(data){
            // 删除数字化图片菜单
            this.$confirm(`确认删除该节点？`,'提示',{
                type:'warning'
            }).then(() => {
                GraphTreeDel(data.node.id).then(res=>{
                    if(res.isSuccess){
                        this.pointMenuForm = {}
                        this.onGetMenuList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                }) 
            }).catch(() => {}); 
        },
        handleChangeMenu(data){
            this.imageUrl = ''
            this.allElementPoint = []
            this.allElementText = []
            this.treeID = data.id 
            this.getPointLink()
        },
        getPointLink(){
           // 获取底图
            getLinkInfo({
                PointTreeID:this.treeID
            }).then(res=>{
                if(res.isSuccess && res.data){ 
                    this.imageUrl = res.data.imgUrl || ''
                    this.pointsLink = res.data.points
                }else{
                    this.imageUrl = ''
                    this.pointsLink = []
                }
            })
        },
        getPointAndText(){
            // 测点和线
            const date = new Date()
            const toDay = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
            GraphPointDraw({
                pointTreeID:this.treeID,
                graphtype:this.drawType,
                w:this.svgW,
                h:this.svgH,
                timeParts:[
                    {
                        dt:toDay,
                        length:365
                    }
                ]
            }).then(res=>{
                if(res.isSuccess){
                    this.allElementPoint = res.data.drawInfos || []
                }else{
                    this.allElementPoint = []
                }
            })

            // 获取文字
            getBwtConfigsByTreeID({
                treeID:this.treeID,
                width:this.svgW,
                height:this.svgH,
                dt:'',
                length:''
            }).then(res=>{
                if(res.isSuccess){
                    this.allElementText = res.data
                }else{
                    this.allElementText = []
                }
            })
        },
        handleImageLoaded(size) {
            this.svgW = size.width
            this.svgH = size.height
            this.getPointAndText()
        },
        handleChangeDrawType(type) {
            this.selectDrawType = type
            if(type == 3){
                this.pointCorrelationDialog = true
            }else if(type == 4){
                getDIR({
                    PointTreeID:this.treeID,
                    CATEGROY:this.drawType
                }).then(res=>{
                    if(res.isSuccess && res.data != null){
                        this.angleForm = res.data
                    }else{
                        this.angleForm = {
                            dirTp: 1,
                            categroy:this.drawType,
                            pointTreeID:this.treeID,
                            angle: 0,
                            clockwise: 1,
                            id:0
                        }
                    }
                })
                this.directionDialogVisible = true
            }else if(type == 5){
              
                // 获取测点分组
                getGroup({
                    PointTreeID:this.treeID,
                    CATEGROY:this.drawType
                }).then(res=>{
                    if(res.isSuccess && res.data.length > 0){
                        const list = []
                        res.data.forEach(item=>{
                            const data ={
                                groupID:item.groupID,
                                points:item.points,
                                selectPoints:[],
                                oldSelectPoints:[]
                            } 
                            item.points.forEach(p=>{
                                data.selectPoints.push(p.codE_ID)
                                data.oldSelectPoints.push(p.codE_ID)
                            })
                            list.push(data)
                        })
                        this.pointGroup = [...list]
                    }else{
                        this.pointGroup = []
                    }
                })

                // 获取分量分组
                getPonits({
                    PointTreeID:this.treeID,
                    CATEGROY:this.drawType
                }).then(res=>{
                    if(res.isSuccess){
                        if(res.data && res.data.length > 0 ){   
                            const list = []
                            res.data.forEach(item=>{
                                const data = {
                                    cGroID:item.cGroID,
                                    points:item.p_Cs.comPs,
                                    names:item.p_Cs.points,
                                    selectPoints:[],
                                    selectComps:[],
                                    oldSelectPoints:[]
                                }
                                // 回显选中comp列表
                                item.p_Cs.comPs.forEach(p=>{
                                    if(p.checked == 1){
                                        data.selectComps.push(p.compid) 
                                    }
                                })
                                // 回显选中point列表
                                item.p_Cs.points.forEach(p=>{ 
                                    data.selectPoints.push(p.codE_ID)
                                })
                                
                                list.push(data)
                            })
                            this.compGroup = list
                        }else{
                            this.compGroup = []
                        }
                        
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
                this.drawSetDialogVisible = true
            }
        },
        handleChangeDrawImageType(type){
            this.drawType = type
            this.getPointAndText()
        },
        handleAssociation(id){
            setLink({
                id:0,
                graphTreeID:id,
                pointTreeID:this.treeID 
            }).then(res=>{
                if(res.isSuccess){
                    this.allElementPoint = []
                    this.allElementText = []
                    this.getPointLink()
                    this.pointCorrelationDialog = false
                }
            })
        },
        handleCancelDir(){
            this.directionDialogVisible = false
            this.angleForm = {}
        },
        handleSaveDir(data){
            if(data.id && data.id != 0){
                GraphPointDIREdit(data).then(res=>{
                    if(res.isSuccess){
                        this.handleCancelDir()
                        this.getPointAndText()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                GraphPointDIRAdd(data).then(res=>{
                    if(res.isSuccess){
                        this.handleCancelDir()
                        this.getPointAndText()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleSavePointGroup(data){
            const _list = []
            const len = Number(data.length)
            data.forEach((item,index)=>{
                item.points.forEach(subItem=>{
                    const data = {
                        id:item.id || 0,
                        pointTreeID: this.treeID,
                        groupID:item.groupID || index - len,
                        categroy:item.categroy || this.drawType,
                        index:subItem.index,
                        codE_ID: subItem.code_ID || subItem.codE_ID
                    }
                    _list.push(data)
                })
            })
            setGroup(_list).then(res=>{
                if(res.isSuccess){
                    this.$message.success('测点设置成功！')
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        handleSaveCompGroup(data){
            const _list = []
            data.forEach(item=>{
                item.points.forEach((subItem)=>{  
                    if(subItem.checked == 1){
                        const _data = {...subItem}
                        _data.cGroID = item.cGroID
                        item.names.forEach(n=>{
                            const nData = {..._data}
                            nData.codE_ID = n.codE_ID
                            nData.pointName = n.pointName
                            _list.push(nData) 
                        })
                        
                    }
                })
            })
            
            if(this.drawType == 3){
                const len = data[0].selectComps.length 
                if(len < 2){
                    this.$message.error('合矢量图必须选2个分量值！')
                    return false
                }else{
                    setCOMP(_list).then(res=>{
                        if(res.isSuccess){
                            this.$message.success('分量设置成功！')
                        }else{
                            this.$message.error(res.errorMessage)
                        }
                    })
                }
            }else{
                setCOMP(_list).then(res=>{
                    if(res.isSuccess){
                        this.$message.success('分量设置成功！')
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
            
        },
         handleSavePointMenu(){
            if(this.menuEdit){
                GraphTreetEdit(this.pointMenuForm).then(res=>{
                    if(res.isSuccess){ 
                        this.handleCancelPointMenu()
                        this.onGetMenuList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                const data = {
                    id: this.pointMenuForm.id || 0,
                    treeID: this.pointMenuForm.treeID || 0,
                    stationID: this.stationId,
                    treeName:this.pointMenuForm.treeName,
                    upTreeID: this.pointMenuForm.upTreeID || 0,
                    isBottom: this.pointMenuForm.isBottom || 0,
                    imgUrl: this.pointMenuForm.imgUrl || '',
                    indexId: this.pointMenuForm.indexId || 0, 
                    categroy:4,
                    imgDate:this.pointMenuForm.imgDate || '',
                    url:this.pointMenuForm.imgDate || '',
                    graphtype:this.pointMenuForm.graphtype || 1
                }
                GraphTreeAdd(data).then(res =>{
                    if(res.isSuccess){ 
                        this.handleCancelPointMenu()
                        this.onGetMenuList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleCancelPointMenu(){
            this.dialogPointMenuVisible =false
            this.pointMenuForm = {}
        }
    }
})
</script>

<style scoped lang="scss">
.imageSet {
  display: flex;
  flex-direction: row;
  justify-content: start;
  margin-top: 10px;
  gap: 5px;
  height: calc(100vh - 180px);
  .menu-tree{
    height: calc(100vh - 240px);
    width:320px;
    overflow: auto;
  }
  
}
.dialog-body {
  padding: 30px;
}

.form-item-custom {
  margin-bottom: 28px;
  
  ::v-deep .el-form-item__label {
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 8px;
    font-size: 14px;
  }
}

.custom-input {
  ::v-deep .el-input__inner {
    height: 48px;
    border-radius: 12px;
    border: 2px solid #e2e8f0;
    font-size: 14px;
    transition: all 0.3s ease;
    
    &:focus {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }
  
  ::v-deep .el-input__prefix {
    left: 15px;
    i {
      color: #a0aec0;
    }
  }
}

.input-tips {
  font-size: 12px;
  color: #a0aec0;
  margin-top: 6px;
}

.type-selector {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 8px;
}

.type-card {
  background: white;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 20px 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
  }
  
  &.active {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
  }
}

.type-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 12px;
  
  i {
    font-size: 24px;
    color: white;
  }
}

.type-label {
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 4px;
  font-size: 14px;
}

.type-desc {
  font-size: 12px;
  color: #718096;
  line-height: 1.4;
}


.dialog-container {
  border-radius: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
  box-shadow: 0 20px 60px rgba(59, 130, 246, 0.15);
}

.dialog-header {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  padding: 30px;
  text-align: center;
  position: relative;
  
  .header-icon {
    width: 60px;
    height: 60px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 15px;
    
    i {
      font-size: 28px;
      color: white;
    }
  }
  
  h3 {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    letter-spacing: 0.5px;
  }
  
  p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
    font-weight: 300;
  }
}

.dialog-body {
  padding: 30px;
}

.form-item-custom {
  margin-bottom: 28px;
  
  ::v-deep .el-form-item__label {
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 8px;
    font-size: 14px;
  }
}

.custom-input {
  ::v-deep .el-input__inner {
    height: 48px;
    border-radius: 12px;
    border: 2px solid #e5e7eb;
    font-size: 14px;
    transition: all 0.3s ease;
    padding-left: 40px;
    
    &:focus {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }
  
  ::v-deep .el-input__prefix {
    left: 15px;
    i {
      color: #9ca3af;
    }
  }
}

.input-tips {
  font-size: 12px;
  color: #6b7280;
  margin-top: 6px;
}

.type-selector {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 8px;
}

.type-card {
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #3b82f6;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.15);
  }
  
  &.active {
    border-color: #3b82f6;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
    
    .type-icon {
      background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    }
    
    .type-label {
      color: #1d4ed8;
    }
  }
}

.type-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #93c5fd 0%, #60a5fa 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 12px;
  transition: all 0.3s ease;
  
  i {
    font-size: 24px;
    color: white;
  }
}

.type-label {
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
  font-size: 14px;
  transition: color 0.3s ease;
}

.type-desc {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}
</style>
